package com.example.service.impl;

import com.example.common.Result;
import com.example.common.PageResult;
import com.example.dto.SupplyProductDTO;
import com.example.entity.SupplyProduct;
import com.example.entity.StockRecord;
import com.example.mapper.SupplyProductMapper;
import com.example.mapper.StockRecordMapper;
import com.example.service.SupplyProductService;
import com.example.util.UserContextUtil;
import com.example.vo.SupplyProductVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Service
public class SupplyProductServiceImpl implements SupplyProductService {
    
    @Autowired
    private SupplyProductMapper supplyProductMapper;
    
    @Autowired
    private StockRecordMapper stockRecordMapper;
    
    @Autowired
    private UserContextUtil userContextUtil;
    
    @Override
    @Transactional
    public Result<Void> addSupplyProduct(SupplyProductDTO supplyProductDTO) {
        try {
            // 自动生成商品编号
            String productCode = generateProductCode();
            
            // 创建商品实体
            SupplyProduct supplyProduct = new SupplyProduct();
            supplyProduct.setProductName(supplyProductDTO.getProductName());
            supplyProduct.setCost(supplyProductDTO.getCost());
            supplyProduct.setProductCode(productCode); // 使用自动生成的编号
            supplyProduct.setModel(supplyProductDTO.getModel());
            supplyProduct.setStock(supplyProductDTO.getStock());
            supplyProduct.setImage(supplyProductDTO.getImage());
            supplyProduct.setSupplierId(supplyProductDTO.getSupplierId());
            supplyProduct.setCategoryId(supplyProductDTO.getCategoryId());
            supplyProduct.setCreateTime(LocalDateTime.now());
            supplyProduct.setUpdateTime(LocalDateTime.now());
            supplyProduct.setDeleted(0);
            
            int result = supplyProductMapper.insert(supplyProduct);
            if (result > 0) {
                // 管理员创建商品时，如果有初始库存，创建入库记录
                if (supplyProductDTO.getStock() != null && supplyProductDTO.getStock() > 0) {
                    createAdminStockInRecord(supplyProduct, supplyProductDTO.getStock(), "管理员创建商品初始入库");
                }
                
                log.info("添加供货商品成功，商品名称: {}, 商品编号: {}, 初始库存: {}", 
                    supplyProductDTO.getProductName(), productCode, supplyProductDTO.getStock());
                return Result.success();
            } else {
                return Result.error("添加供货商品失败");
            }
        } catch (Exception e) {
            log.error("添加供货商品失败", e);
            return Result.error("添加供货商品失败");
        }
    }
    
    /**
     * 生成商品编号
     * 格式：SP + 年月日 + 4位序号，例如：SP202501150001
     */
    private String generateProductCode() {
        LocalDateTime now = LocalDateTime.now();
        String dateStr = String.format("%04d%02d%02d", now.getYear(), now.getMonthValue(), now.getDayOfMonth());
        
        // 查询当天已有的商品数量
        String prefix = "SP" + dateStr;
        int count = supplyProductMapper.countByProductCodePrefix(prefix);
        
        // 生成4位序号
        String sequence = String.format("%04d", count + 1);
        
        return prefix + sequence;
    }
    
    /**
     * 创建管理员入库记录
     * 管理员创建商品时的初始库存算作入库
     */
    private void createAdminStockInRecord(SupplyProduct supplyProduct, Integer quantity, String remark) {
        try {
            // 获取当前管理员信息
            Long operatorId = userContextUtil.getCurrentUserId();
            String operatorName = userContextUtil.getCurrentUserNickname();
            if (operatorName == null || operatorName.trim().isEmpty()) {
                operatorName = userContextUtil.getCurrentUsername();
                if (operatorName == null || operatorName.trim().isEmpty()) {
                    operatorName = "管理员";
                }
            }
            
            StockRecord stockRecord = new StockRecord();
            stockRecord.setRecordNo(generateStockRecordNo());
            stockRecord.setProductId(supplyProduct.getId());
            stockRecord.setProductName(supplyProduct.getProductName());
            stockRecord.setProductCode(supplyProduct.getProductCode());
            stockRecord.setRecordType("IN"); // 入库
            stockRecord.setQuantity(quantity);
            stockRecord.setBeforeStock(0); // 创建商品前库存为0
            stockRecord.setAfterStock(quantity); // 创建后库存为初始库存
            stockRecord.setUnitCost(supplyProduct.getCost());
            if (supplyProduct.getCost() != null) {
                stockRecord.setTotalCost(supplyProduct.getCost().multiply(new java.math.BigDecimal(quantity)));
            }
            stockRecord.setOperatorId(operatorId);
            stockRecord.setOperatorName(operatorName);
            stockRecord.setRemark(remark);
            stockRecord.setCreateTime(LocalDateTime.now());
            stockRecord.setUpdateTime(LocalDateTime.now());
            stockRecord.setDeleted(0);
            
            stockRecordMapper.insert(stockRecord);
            log.info("创建管理员入库记录成功，商品: {}, 数量: {}", supplyProduct.getProductName(), quantity);
        } catch (Exception e) {
            log.error("创建管理员入库记录失败", e);
        }
    }
    
    /**
     * 创建管理员出库记录
     * 管理员调整库存减少时的出库记录
     */
    private void createAdminStockOutRecord(SupplyProduct supplyProduct, Integer quantity, Integer beforeStock, Integer afterStock, String remark) {
        try {
            // 获取当前管理员信息
            Long operatorId = userContextUtil.getCurrentUserId();
            String operatorName = userContextUtil.getCurrentUserNickname();
            if (operatorName == null || operatorName.trim().isEmpty()) {
                operatorName = userContextUtil.getCurrentUsername();
                if (operatorName == null || operatorName.trim().isEmpty()) {
                    operatorName = "管理员";
                }
            }
            
            StockRecord stockRecord = new StockRecord();
            stockRecord.setRecordNo(generateStockRecordNo());
            stockRecord.setProductId(supplyProduct.getId());
            stockRecord.setProductName(supplyProduct.getProductName());
            stockRecord.setProductCode(supplyProduct.getProductCode());
            stockRecord.setRecordType("OUT"); // 出库
            stockRecord.setQuantity(quantity);
            stockRecord.setBeforeStock(beforeStock);
            stockRecord.setAfterStock(afterStock);
            stockRecord.setUnitCost(supplyProduct.getCost());
            if (supplyProduct.getCost() != null) {
                stockRecord.setTotalCost(supplyProduct.getCost().multiply(new java.math.BigDecimal(quantity)));
            }
            stockRecord.setOperatorId(operatorId);
            stockRecord.setOperatorName(operatorName);
            stockRecord.setRemark(remark);
            stockRecord.setCreateTime(LocalDateTime.now());
            stockRecord.setUpdateTime(LocalDateTime.now());
            stockRecord.setDeleted(0);
            
            stockRecordMapper.insert(stockRecord);
            log.info("创建管理员出库记录成功，商品: {}, 数量: {}", supplyProduct.getProductName(), quantity);
        } catch (Exception e) {
            log.error("创建管理员出库记录失败", e);
        }
    }
    
    /**
     * 生成库存记录编号
     */
    private String generateStockRecordNo() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        return "SR" + timestamp + random;
    }
    
    @Override
    @Transactional
    public Result<Void> deleteSupplyProduct(Long id) {
        try {
            SupplyProduct supplyProduct = supplyProductMapper.selectById(id);
            if (supplyProduct == null) {
                return Result.error("商品不存在");
            }
            
            int result = supplyProductMapper.deleteById(id);
            if (result > 0) {
                log.info("删除供货商品成功，商品ID: {}", id);
                return Result.success();
            } else {
                return Result.error("删除供货商品失败");
            }
        } catch (Exception e) {
            log.error("删除供货商品失败，商品ID: {}", id, e);
            return Result.error("删除供货商品失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> updateSupplyProduct(Long id, SupplyProductDTO supplyProductDTO) {
        try {
            SupplyProduct existingProduct = supplyProductMapper.selectById(id);
            if (existingProduct == null) {
                return Result.error("商品不存在");
            }
            
            // 记录库存变化
            Integer oldStock = existingProduct.getStock();
            Integer newStock = supplyProductDTO.getStock();
            
            // 更新商品信息（不更新商品编号，因为它是自动生成的）
            existingProduct.setProductName(supplyProductDTO.getProductName());
            existingProduct.setCost(supplyProductDTO.getCost());
            // 不更新商品编号：existingProduct.setProductCode(supplyProductDTO.getProductCode());
            existingProduct.setModel(supplyProductDTO.getModel());
            existingProduct.setStock(supplyProductDTO.getStock());
            existingProduct.setImage(supplyProductDTO.getImage());
            existingProduct.setSupplierId(supplyProductDTO.getSupplierId());
            existingProduct.setCategoryId(supplyProductDTO.getCategoryId());
            existingProduct.setUpdateTime(LocalDateTime.now());
            
            int result = supplyProductMapper.updateById(existingProduct);
            if (result > 0) {
                // 如果库存有变化，创建相应的库存记录
                if (newStock != null && oldStock != null && !newStock.equals(oldStock)) {
                    int stockChange = newStock - oldStock;
                    if (stockChange > 0) {
                        // 库存增加，创建入库记录
                        createAdminStockInRecord(existingProduct, stockChange, "管理员调整库存入库");
                    } else if (stockChange < 0) {
                        // 库存减少，创建出库记录
                        createAdminStockOutRecord(existingProduct, Math.abs(stockChange), oldStock, newStock, "管理员调整库存出库");
                    }
                }
                
                log.info("更新供货商品成功，商品ID: {}, 库存变化: {} -> {}", id, oldStock, newStock);
                return Result.success();
            } else {
                return Result.error("更新供货商品失败");
            }
        } catch (Exception e) {
            log.error("更新供货商品失败，商品ID: {}", id, e);
            return Result.error("更新供货商品失败");
        }
    }
    
    @Override
    public Result<SupplyProductVO> getSupplyProductById(Long id) {
        try {
            SupplyProductVO supplyProductVO = supplyProductMapper.selectVOById(id);
            if (supplyProductVO == null) {
                return Result.error("商品不存在");
            }
            return Result.success(supplyProductVO);
        } catch (Exception e) {
            log.error("查询供货商品失败，商品ID: {}", id, e);
            return Result.error("查询供货商品失败");
        }
    }
    
    @Override
    public Result<List<SupplyProductVO>> getAllSupplyProducts() {
        try {
            List<SupplyProductVO> supplyProducts = supplyProductMapper.selectVOList(new SupplyProduct());
            return Result.success(supplyProducts);
        } catch (Exception e) {
            log.error("查询所有供货商品失败", e);
            return Result.error("查询供货商品列表失败");
        }
    }
    
    @Override
    public Result<PageResult<SupplyProductVO>> getSupplyProductPage(int page, int size, String keyword) {
        try {
            int offset = (page - 1) * size;
            List<SupplyProductVO> supplyProducts = supplyProductMapper.selectPage(offset, size, keyword);
            
            // 使用新的统计方法来计算总数
            long total = supplyProductMapper.selectPageCount(keyword);
            
            PageResult<SupplyProductVO> pageResult = new PageResult<>(page, size, total, supplyProducts);
            
            log.info("分页查询供货商品成功，页码: {}, 大小: {}, 关键词: {}, 总数: {}, 结果数: {}", 
                    page, size, keyword, total, supplyProducts.size());
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询供货商品失败，页码: {}, 大小: {}, 关键词: {}", page, size, keyword, e);
            return Result.error("分页查询供货商品失败");
        }
    }
    
    @Override
    public Result<Boolean> checkProductCodeExists(String productCode, Long excludeId) {
        try {
            SupplyProduct existingProduct;
            if (excludeId != null) {
                existingProduct = supplyProductMapper.selectByProductCodeExcludeId(productCode, excludeId);
            } else {
                existingProduct = supplyProductMapper.selectByProductCode(productCode);
            }
            return Result.success(existingProduct != null);
        } catch (Exception e) {
            log.error("检查商品编号是否存在失败，商品编号: {}", productCode, e);
            return Result.error("检查商品编号失败");
        }
    }
} 